package com.captainbank.tcl.tclapplication.ui.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by TCL on 2019/9/17.
 * Describe:
 */
public class SMSReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //获取短信
        getMsg(context,intent);
    }

    private void getMsg(Context context, Intent intent) {
        //pdus短信单位pdu
        //解析短信内容
        Bundle bundle = intent.getExtras();
        if(bundle!=null){
            Object[] pdus = (Object[]) bundle.get("pdus");
            assert pdus != null;
            for (Object pdu : pdus) {
                //封装短信参数的对象
                SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu);
                String number = sms.getOriginatingAddress();
                String body = sms.getMessageBody();
                //获取短信验证码
                getCode(context, body);
            }
        }
    }

    private void getCode(Context context, String body) {
        Pattern pattern1 = Pattern.compile("(\\d{6})");//提取六位数字
        Matcher matcher1 = pattern1.matcher(body);//进行匹配

        Pattern pattern2 = Pattern.compile("(\\d{4})");//提取四位数字
        Matcher matcher2 = pattern2.matcher(body);//进行匹配

        if (matcher1.find()) {//匹配成功
            String code = matcher1.group(0);
            System.out.println("输出6位验证码：" + code);
        } else if (matcher2.find()) {
            String code = matcher2.group(0);
            System.out.println("输出4位验证码：" + code);
        }

    }

}
